package com.nanmeishu.services.tale.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.nanmeishu.infrastructure.web.entity.ResponseResult;
import com.nanmeishu.infrastructure.web.util.ResultUtil;
import com.nanmeishu.services.tale.entity.Tale;
import com.nanmeishu.services.tale.entity.TaleDetails;
import com.nanmeishu.services.tale.facade.TaleService;
import com.nanmeishu.util.DataUtil;
import com.nanmeishu.util.JwtUtil;
import com.nanmeishu.web.TokenVerifyAnnotation;
import io.swagger.annotations.*;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.net.ssl.SSLContext;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.math.BigDecimal;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;

@Api(tags = "故事模块接口")
@RequestMapping("/tale")
@RestController
public class TaleController {

    @Autowired
    TaleService taleService;

    @Value("${caiHongPiImg}")
    String caiHongPiImg;

    @TokenVerifyAnnotation
    @ApiOperation("新增/修改地图故事明细")
    @PostMapping("/saveTaleDetails")
    public ResponseResult saveTaleDetails(@RequestBody TaleDetails taleDetails){
        taleService.saveTaleDetails(taleDetails);
        return ResultUtil.success();
    }

    @TokenVerifyAnnotation
    @GetMapping("/listTaleByDitu")
    @ApiOperation("市级地图故事集合")
    public ResponseResult<List<Tale>> listTaleByDitu(HttpServletRequest req,@Param("dituName") String dituName){
        String userId = JwtUtil.get(req.getHeader("accessToken"), "userId");
        List<Tale> tales= taleService.listTaleByDitu(userId,dituName);
        return ResultUtil.success(tales);
    }

    @ApiOperation("获取记录的城市信息")
    @GetMapping("/listCityName")
    public ResponseResult<List<String>> listCityName(HttpServletRequest req){
        String userId = JwtUtil.get(req.getHeader("accessToken"), "userId");
       List<String> names= taleService.listCityName(userId);
        return ResultUtil.success(names);
    }


    @ApiOperation("/新增故事及其明细")
    @PostMapping("/saveTaleAndDetails")
    public ResponseResult saveTaleAndDetails(@RequestBody Tale tale, HttpServletRequest req) {
        String userId = JwtUtil.get(req.getHeader("accessToken"), "userId");
        taleService.saveTaleAndDetails(tale,userId);
        return ResultUtil.success();
    }

    @ApiOperation("标记地图")
    @PostMapping("/signTaleDitu")
    public ResponseResult signTaleDitu(@RequestBody Tale tale, HttpServletRequest req){
        String userId = JwtUtil.get(req.getHeader("accessToken"), "userId");
        taleService.signTaleDitu(tale,userId);
        return ResultUtil.success();
    }


    @ApiOperation("获取用户故事列表")
    @GetMapping("/listByUserId")
    @ApiImplicitParam(name = "userId", value = "用户id", required = true)
    @ApiResponses({
            @ApiResponse(code = 200, message = "tales:故事对象", response = Tale.class)
    })
    public ResponseResult listByUserId(@RequestParam("userId") String userId,
                                       @RequestParam("pageNum") String pageNum,
                                       @RequestParam("pageSize") String pageSize) {
        DataUtil.verifyData(userId, "用户id/userId");
        return ResultUtil.success(taleService.listByUserId(userId, pageNum, pageSize));
    }

    @ApiOperation("更新故事信息")
    @TokenVerifyAnnotation
    @PostMapping("/updateTaleAndDetails")
    public ResponseResult updateTaleAndDetails(@RequestBody Tale tale) {
        updateTaleAndDetailsVerifyData(tale);
        taleService.updateTaleAndDetails(tale);
        return ResultUtil.success();
    }

    // 更新故事信息--数据有效性验证
    private void updateTaleAndDetailsVerifyData(Tale tale) {
        DataUtil.verifyData(tale.getTaleId(), "故事ID/taleId");
    }


    @TokenVerifyAnnotation
    @ApiOperation("获取用户故事列表通过token")
    @GetMapping("/listByToken")
    public ResponseResult listByToken(HttpServletRequest req,
                                      @RequestParam("pageNum") String pageNum,
                                      @RequestParam("pageSize") String pageSize) {
        String token = req.getHeader("accessToken");
        String userId = JwtUtil.get(token, "userId");
        return listByUserId(userId, pageNum, pageSize);
    }

    @ApiOperation("获取彩虹屁")
    @ApiResponses({
            @ApiResponse(code = 200, message = "text:彩虹屁文字，img：彩虹屁url", response = Map.class)
    })
    @GetMapping("/getCaiHongPi")
    public ResponseResult getCaiHongPi() {
        Map<String, String> caihongpiMap = new HashMap<>();
        String caihongpiText;
        caihongpiText = taleService.caiHongPiText();
//        try {
//            String caihongpiImg = caiHongPiImg();
//            if (caihongpiImg == null) {
//                throw new RuntimeException("彩虹屁图片获取失败");
//            }
//            caihongpiMap.put("img", caihongpiImg);
//
//        }catch (Exception e){
//            caihongpiMap.put("img", "https://img.zcool.cn/community/01a3a2599c3deba80121ad7b597cab.jpg@1280w_1l_2o_100sh.jpg");
//        }
        caihongpiMap.put("img", "https://img.zcool.cn/community/01a3a2599c3deba80121ad7b597cab.jpg@1280w_1l_2o_100sh.jpg");
        caihongpiMap.put("text", caihongpiText);
        return ResultUtil.success(caihongpiMap);
    }

    /**
     * 获取彩虹屁图片Url
     */
    private String caiHongPiImg() {
        CloseableHttpClient httpclient = null;
        CloseableHttpResponse response = null;
        try {
            SSLContext sslContext = SSLContextBuilder.create().loadTrustMaterial(null, (X509Certificate[] x509Certificates, String s) -> true).build();
            SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, new String[]{"SSLv3", "TLSv1", "TLSv1.2"}, null, NoopHostnameVerifier.INSTANCE);
//            httpclient = HttpClients.createDefault();
            httpclient = HttpClientBuilder.create().setSSLSocketFactory(sslSocketFactory).build();
//            HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
//            requestFactory.setHttpClient(httpclient);
//            restTemplate = new RestTemplate(requestFactory);
            HttpGet httpGetTest1 = new HttpGet(caiHongPiImg);
            response = httpclient.execute(httpGetTest1);
            // 4.获取响应实体
            HttpEntity entityTest = response.getEntity();
            Map map = JSON.parseObject(EntityUtils.toString(entityTest, "utf-8"), Map.class);
            String imgurl = map
                    .get("imgurl").toString();
            return imgurl;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                throw new RuntimeException("加载彩虹屁出错，请重新进入此页面");
            }
        }
        return null;
    }

    @ApiOperation("通过用户Id统计日记数量")
    @GetMapping("/countTaleByUserId")
    public ResponseResult countTaleByUserId(@RequestParam("userId") String userId){
        return ResultUtil.success(taleService.countTaleByUserId(userId));
    }

    @ApiOperation("删除指定日记")
    @TokenVerifyAnnotation
    @GetMapping("/deleteTale")
    public ResponseResult deleteTale(@RequestParam("taleId") String taleId,HttpServletRequest request){
        String userId= JwtUtil.get(request.getHeader("accessToken"),"userId");
        taleService.deleteTale(userId,taleId);
        return ResultUtil.success();
    }

    @ApiOperation("通过taleid获取详细信息")
    @GetMapping("/getTale")
    public ResponseResult getTale(@RequestParam("taleId") String taleId){
        Tale tale= taleService.getTale(taleId);
        return ResultUtil.success(tale);
    }

    private static String currentPath() {
        File dir = new File(".");
        String currentpath = "";
        try {
            currentpath = dir.getCanonicalPath();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return currentpath;
    }

    public static String readJsonData(String pactFile) throws IOException {
        // 读取文件数据
        //System.out.println("读取文件数据util");

        StringBuffer strbuffer = new StringBuffer();
        File myFile = new File(pactFile);//"D:"+File.separatorChar+"DStores.json"
        if (!myFile.exists()) {
            System.err.println("Can't Find " + pactFile);
        }
        try {
            FileInputStream fis = new FileInputStream(pactFile);
            InputStreamReader inputStreamReader = new InputStreamReader(fis, "UTF-8");
            BufferedReader in  = new BufferedReader(inputStreamReader);

            String str;
            while ((str = in.readLine()) != null) {
                strbuffer.append(str);  //new String(str,"UTF-8")
            }
            in.close();
        } catch (IOException e) {
            e.getStackTrace();
        }
        //System.out.println("读取文件结束util");
        return strbuffer.toString();
    }

    public static void main(String[] args) throws IOException {
        String json=readJsonData(currentPath() + "/static/ditu/台湾省.json");
        Map map = JSON.parseObject(json, Map.class);
        List<Map> features = JSON.parseArray(JSON.toJSONString(map.get("features")), Map.class);
        String sql="insert into tt_atlas_city_coord(city_name,x_number,y_number,city_code,parant_id,focus) values";
        Map properties;
        Integer type=1220;
        List<BigDecimal> numbers;
        Integer i=1;
        for (Map feature : features) {
            properties = JSON.parseObject(JSON.toJSONString(feature.get("properties")), Map.class);
            System.out.println(properties.get("name"));
            numbers=JSON.parseArray(JSON.toJSONString(properties.get("center")),BigDecimal.class);
            sql=sql+"('";
            sql+=properties.get("name");
            sql+="',";
            sql+=numbers.get(0);
            sql+=",";
            sql+=numbers.get(1);
            sql+=",";
            sql=sql+"'";
            sql+=properties.get("name");
            sql+="',";
            sql+=type;
            sql+=",";
            if(i==1){
                sql+="1";
            }else {
                sql+="0";
            }
            i++;
            sql+="),";
        }
        sql=sql.substring(0,sql.length()-1);
        sql+=";";
        System.out.println(sql);
    }

}
